<script setup>
import {ref, reactive} from 'vue';
import {message} from 'ant-design-vue';
import axios from 'axios';
import {
  UserOutlined,
  ClockCircleOutlined,
  SafetyCertificateOutlined,
  IdcardOutlined,
  HomeOutlined,
  CompassOutlined,
  ColumnHeightOutlined,
  CalendarOutlined,
  BankOutlined,
  PhoneOutlined,
  TransactionOutlined
} from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import { useRouter} from "vue-router";

const router = useRouter();
const formState = reactive({
  date: null,
  time: null,
  name: '',
  phone: '',
  remark: ''
});
const houseId = sessionStorage.getItem("houseId");
const token = localStorage.getItem("access-token");
const ownerId = sessionStorage.getItem("ownerId");
const house = ref({});
const houseImages = ref([]);
const userInfo = ref({});

const setHouse = async () => {
  try {
    const response = await axios.get(`${window.link}/house/${houseId}`, {
      headers: {
        "access-token": `${token}`, // 使用标准头代替自定义头
      },
    });
    console.log(response)
    if (response.data.code === 200) {
      house.value = response.data.data.house;
      userInfo.value = response.data.data.userInfo;
      houseImages.value = response.data.data.graphs;
      
    } else {
      message.error(response.data.message)
    }
  } catch (error) {
    console.error("获取详细信息失败", error)
  }
}

const videoExtensions = ['mp4', 'webm', 'ogg']
const isVideo = () => {
  console.log(houseImages.value[0])
  const extension = houseImages.value[0].url.split('.').pop().toLowerCase()
  return videoExtensions.includes(extension)
}

const agent = reactive({
  avatar: userInfo.value.avatar,
  name: userInfo.value.name,
});

const notices = [
  {
    icon: ClockCircleOutlined,
    title: '预约时间',
    content: '请提前24小时预约，我们会尽快确认并安排看房事宜'
  },
  {
    icon: SafetyCertificateOutlined,
    title: '防疫要求',
    content: '看房时请佩戴口罩，保持社交距离，配合体温检测'
  },
  {
    icon: IdcardOutlined,
    title: '携带证件',
    content: '看房时请携带有效身份证件，以便办理访客登记'
  }
];
const disabledDate = (current) => {
  return current && current < dayjs().startOf('day');
};

const disabledTime = () => {
  return {
    disabledHours: () => [0, 1, 2, 3, 4, 5, 6, 7, 22, 23],
  };
};

// 添加电话验证函数
const validatePhone = (phone) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
};

const handleSubmit = async () => {
  if (!formState.date || !formState.time || !formState.name || !formState.phone) {
    message.error('请填写完整预约信息');
    return;
  }
  if (!validatePhone(formState.phone)) {
    message.error('请输入正确的手机号码');
    return;
  }
  try {
    const data = JSON.stringify({
      houseId: houseId,
      ownerId: ownerId,
      date: dayjs(formState.date).format('YYYY-MM-DD'),
      time: dayjs(formState.time).format('HH:mm:ss'),
      name: formState.name,
      phone: formState.phone,
      remark: formState.remark
    })
    console.log(data)
    const response = await axios.post(`${window.link}/user/reserve`, data,{
      headers:{
        "access-token": `${token}`,
        "Content-Type": "application/json"
      }
    });
    if (response.data.code === 200) {
      message.success(response.data.message)
      setTimeout(()=>{
        router.push("/house")
      },500)
    } else {
      message.error(response.data.message)
    }
  } catch (error) {
    console.error("预约失败", error)
  }
};

setHouse();
</script>
<template>
  <div class="min-h-[1024px] w-[1440px] mx-auto bg-gray-50 py-8">
    <div class="container mx-auto px-8">
      <!-- 搜索区域 -->
      <div class="bg-white rounded-lg shadow-md p-8 mb-8">
        <h2 class="text-2xl font-bold mb-6">预约看房</h2>
        <div class="grid grid-cols-2 gap-8">
          <div>
            <a-form :model="formState" layout="vertical">
              <a-form-item label="看房日期">
                <a-date-picker
                    v-model:value="formState.date"
                    format="YYYY-MM-DD"
                    class="w-full !rounded-button"
                    :disabled-date="disabledDate"
                />
              </a-form-item>
              <a-form-item label="看房时间">
                <a-time-picker
                    v-model:value="formState.time"
                    format="HH:mm"
                    class="w-full !rounded-button"
                    :disabled-time="disabledTime"
                />
              </a-form-item>
              <a-form-item label="联系人">
                <a-input
                    v-model:value="formState.name"
                    placeholder="请输入您的姓名"
                    class="!rounded-button"
                >
                  <template #prefix>
                    <user-outlined/>
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item 
                  label="联系电话" 
                  :validateStatus="formState.phone && !validatePhone(formState.phone) ? 'error' : ''"
                  :help="formState.phone && !validatePhone(formState.phone) ? '请输入正确的手机号码' : ''">
                <a-input
                    v-model:value="formState.phone"
                    placeholder="请输入您的手机号码"
                    class="!rounded-button"
                >
                  <template #prefix>
                    <phone-outlined/>
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item label="备注信息">
                <a-textarea
                    v-model:value="formState.remark"
                    placeholder="请输入您的特殊要求或其他备注信息"
                    :rows="4"
                    class="!rounded-button"
                />
              </a-form-item>
              <a-button type="primary" block @click="handleSubmit" class="!rounded-button whitespace-nowrap">
                提交预约
              </a-button>
            </a-form>
          </div>

          <div class="bg-white mt-4 p-6">
            <img
                v-if="!isVideo()"
                :src="houseImages[0].url"
                class="w-full h-48 object-cover rounded-lg mb-4"
            />
            <video
                v-else
                :src="houseImages[0].url"
                class="w-full h-48 object-cover rounded-lg mb-4"
            />
            <h2 class="text-xl font-bold mb-4">房屋信息</h2>
            <div class="grid grid-cols-3 gap-4">
              <div class="flex items-center">
                <home-outlined class="text-gray-500 mr-2"/>
                <span>建筑面积：{{ house.area }}㎡</span>
              </div>
              <div class="flex items-center">
                <compass-outlined class="text-gray-500 mr-2"/>
                <span>朝向：{{ house.orientation }}</span>
              </div>
              <div class="flex items-center">
                <column-height-outlined class="text-gray-500 mr-2"/>
                <span>楼层：{{ house.floor }}层</span>
              </div>
              <div class="flex items-center">
                <transaction-outlined class="text-gray-500 mr-2"/>
                <span>装修：{{ house.decoration }}</span>
              </div>
              <div class="flex items-center">
                <calendar-outlined class="text-gray-500 mr-2"/>
                <span>户型：{{ house.layout }}</span>
              </div>
              <div class="flex items-center">
                <bank-outlined class="text-gray-500 mr-2"/>
                <span>租约方式：{{ house.rentalMethod }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 看房须知 -->
      <div class="bg-white rounded-lg shadow-md p-8">
        <h3 class="text-xl font-bold mb-4">看房须知</h3>
        <div class="grid grid-cols-3 gap-6">
          <div v-for="(notice, index) in notices" :key="index" class="flex items-start space-x-3">
            <div class="flex-shrink-0 w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center">
              <component :is="notice.icon" class="text-blue-600"/>
            </div>
            <div>
              <h4 class="font-medium mb-1">{{ notice.title }}</h4>
              <p class="text-gray-600 text-sm">{{ notice.content }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<style scoped>
:deep(.ant-picker) {
  width: 100%;
}
</style>

